package com.njcky.controller;

import com.njcky.model.SectionLine;
import com.njcky.model.dto.InParamDto;
import com.njcky.model.dto.MultiTypeReqDto;
import com.njcky.model.dto.QueryPipelineLengthDTO;
import com.njcky.model.dto.SectionAnalysisDto;
import com.njcky.model.vo.SectionAnalysisVo;
//import com.njcky.service.JianJunRoadDemoService;
//import com.njcky.service.ProjectPptimizationService;
//import com.njcky.service.ConnectivityDistanceAnalysis;
import com.njcky.service.ConnectivityDistanceAnalysisNew;
import com.njcky.service.ProjectPptimizationService;
import com.njcky.utils.page.AjaxResult;
import com.njcky.utils.page.BaseController;
import com.njcky.utils.page.entity.TableDataInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/ycjjl")
public class ProjectPptimizationController extends BaseController {

    @Value("${url.hdmurl}")
    private String hdmurl;

    @Value("${url.zdmurl}")
    private String zdmurl;


    @Autowired
    private ProjectPptimizationService projectPptimizationService;

    @Autowired
    private ConnectivityDistanceAnalysisNew connectivityDistanceAnalysis;


    /**
     * 1-6 接口数据优化查询返回
     *
     * @param inParamDto
     * @return
     */
    @PostMapping("/attributeSearch")
    public TableDataInfo attributeSearch(@RequestBody InParamDto inParamDto) {
        // 1. 参数校验增强
        if (ObjectUtils.isEmpty(inParamDto.getTables()) || inParamDto.getTables().isEmpty()) {
            return paramCheck("数据集不能为空");
        }
        List<String> historyParams = inParamDto.getHistoryQueryParam();
        List<Object> historyValues = inParamDto.getHistoryQueryParamValue();
        // 校验参数与值的数量一致性（包括非空判断）
        if ((historyParams != null && !historyParams.isEmpty())
                || (historyValues != null && !historyValues.isEmpty())) {
            if (historyParams == null || historyValues == null
                    || historyParams.size() != historyValues.size()) {
                return paramCheck("属性值与字段数量不一致");
            }
        }
        // 3. 执行查询
        TableDataInfo tableData = new TableDataInfo();
        List<Map<String, Object>> resultList = projectPptimizationService.attributeSearch(inParamDto);
        if (resultList == null) {
            tableData.setMsg("未获取到有效数据！");
            tableData.setTotal(0);
            tableData.setCode(409);
            tableData.setData(new ArrayList<>());
            return tableData;
        }
        List<Map<String, Object>> processedList = this.projectPptimizationService.processResultList(resultList);
        if (processedList.size() == 0) {
            tableData.setMsg("未获取到有效数据！");
            tableData.setTotal(0);
            tableData.setCode(409);
            tableData.setData(new ArrayList<>());
            return tableData;
        }
        int count = Integer.parseInt(processedList.get(0).get("ctest").toString());
        if (!processedList.isEmpty()) {
            // 从第一条数据中获取ctest的值（假设所有数据的ctest相同，仅用于计数）
            Object ctestObj = processedList.get(0).get("ctest");
            if (ctestObj instanceof Number) {
                count = ((Number) ctestObj).intValue();
            }
            // 遍历所有Map，移除"ctest"字段
            for (Map<String, Object> map : processedList) {
                map.remove("ctest"); // 移除字段
            }
        }
        tableData.setMsg("查询成功");
        tableData.setTotal(count);
        tableData.setCode(200);
        tableData.setData(processedList);
        return tableData;
    }




    /**
     * 纵断面分析
     *
     * @param dto
     * @return
     */
    @PostMapping("/querySectionAnalysis")
    public AjaxResult querySectionAnalysis(@RequestBody SectionAnalysisDto dto) {
        SectionAnalysisVo sectionAnalysisVo = projectPptimizationService.querySectionAnalysis(dto);
        if (ObjectUtils.isEmpty(sectionAnalysisVo)) {
            return AjaxResult.error(409, "请确认所分析管线!");
        }
        List<SectionLine> sectionLineList = sectionAnalysisVo.getSectionLineList();
        // 查找匹配的那条记录
        SectionLine matchedLine = null;
        for (SectionLine sectionLine : sectionLineList) {
            if (dto.getFeaturecode().equals(sectionLine.getBh())) {
                matchedLine = sectionLine;
                break; // 找到后退出循环
            }
        }
        // 清空原列表并添加匹配的记录（如果存在）
        sectionLineList.clear();
        if (matchedLine != null) {
            sectionLineList.add(matchedLine);
        }
        AjaxResult re = new AjaxResult(200, "操作成功", sectionAnalysisVo);
        re.put("url", zdmurl);
        return re;
    }


    /**
     * 横断面分析 notes = "【v1.0.2】 横断面分析，返回与传入线相交的管线的各种计算数据"
     *
     * @param req
     * @return
     * @throws Exception
     */
    @PostMapping("/queryCrossSectionAnalysis")
    public AjaxResult queryCrossSectionAnalysis(@RequestBody MultiTypeReqDto req) throws Exception {
        String spatialDtoWKT = req.getGeoCompareModels().get(0).getGeoValueFilter().getGeoValue();
        AjaxResult re = new AjaxResult(200, "操作成功", projectPptimizationService.queryCrossSectionAnalysis(req));
        re.put("distance", projectPptimizationService.calcDistance(spatialDtoWKT));
        re.put("url", hdmurl);
        return re;
    }



/****************************************************【下面两个接口走的pg的拓扑关系库】***************************************************/

    /**
     * 连通性分析返回数据
     *
     * @param dto
     * @return
     */
    @PostMapping("/connectivity")
    public AjaxResult connectivity(@RequestBody QueryPipelineLengthDTO dto) {
        TableDataInfo objects = connectivityDistanceAnalysis.connectivityPublic(dto);
        if (ObjectUtils.isEmpty(objects)) {
            return AjaxResult.error(409, "管线不连通!");
        }
        List<?> rawDataList = objects.getData();
        List<Map<String, Object>> processedDataList = connectivityDistanceAnalysis.processDataFromTableData(rawDataList);
        objects.setData(processedDataList);
        return AjaxResult.success(objects);
    }


    /**
     * 基于连通性分析，获取管线距离（纵断面分析）
     *
     * @param dto
     * @return
     */
    @PostMapping("/queryPipelineNetworkSpacing")
    public AjaxResult queryPipelineLength(@RequestBody QueryPipelineLengthDTO dto) {
        Map<String, Object> resultMap = connectivityDistanceAnalysis.queryPipelineLength(dto);
        if (ObjectUtils.isEmpty(resultMap)){
            return AjaxResult.error(409,"未获取到管线有效长度！");
        }
        return AjaxResult.success(resultMap);
    }

}